package com.vic.framework.helper;

import java.lang.reflect.Field;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;

import com.vic.framework.annotation.Inject;
import com.vic.framework.utils.ReflectionUtil;


/**
 * 依赖注入辅助类
 * @author VIC
 *
 */
public final class IocHelper {

	static {
		//获取所有的bean类和实体的映射关系
		Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
		if(MapUtils.isNotEmpty(beanMap)) {
			for(Map.Entry<Class<?>, Object> entry :beanMap.entrySet()) {
				//获得bean class和bean实例
				Class<?> beanClass = entry.getKey();
				Object beanInstance = entry.getValue();
				
				//获得对象的属性
				Field[] fields = beanClass.getDeclaredFields();
				if(ArrayUtils.isNotEmpty(fields)) {
					for(Field field : fields) {
						//加了Inject注解的属性就注入
						if(field.isAnnotationPresent(Inject.class)) {
							Class<?> beanFieldClass = field.getType();
							Object beanFieldInstance = beanMap.get(beanFieldClass);
							if(beanFieldInstance != null) {
								ReflectionUtil.setField(beanInstance, field, beanFieldInstance);
							}
						}
					}
				}
			}
		}
				
	}

}
